package com.devicemantra.coordinate.ds.tests;
import com.devicemantra.coordinate.dataobjects.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.devicemantra.coordinate.dataobjects.CDepartmentFactory;
import com.devicemantra.coordinate.util.CExcelReader;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.ParamPart;
import com.oreilly.servlet.multipart.Part;


public class ExcelFileReceiver extends HttpServlet 
{
	private String mDeptName = null;
	private String mLocationId = null;
	
	private void setDepartmentName(String pDeptName)
	{
		mDeptName = pDeptName;
	}
	
	private void setLocationId(String pLocationId)
	{
		mLocationId = pLocationId;
	}
	
	
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException,IOException 
	{
		String lMessage = null;
		ArrayList<CContact> lListContacts = null;
		/* First let us create a parser for the incoming multipart form-data */
		MultipartParser lMultipartParser = new MultipartParser(req,1000000);
		while( true )
		{
			Part lPart = lMultipartParser.readNextPart();
			if( lPart == null )
				break;
			
			/* Check whether this Part is a file or a form field ? */
			if( lPart.isParam() )
			{
				ParamPart lParamPart = (ParamPart ) lPart;
				String lName = lPart.getName();
				String lValue = lParamPart.getStringValue();
				/* Process the parameter */
				updateParameter(lName,lValue);
			}
			else 
			{
				/* It's a file , process the file */
				FilePart lFilePart = (FilePart)lPart;
				System.out.println("File  name is " + lPart.getName() + " Value is " + lFilePart.getFileName());
				InputStream lInputStream = lFilePart.getInputStream();
				CExcelReader lReader = new CExcelReader(lInputStream);
	        	lListContacts = lReader.getContacts();
	        	System.out.println("Number of contacts found :  " + lListContacts.size());
	        	lMessage =  lListContacts.size() + " contacts added.";
	        }
		} 
		
		/* Let us set the location id and department for all the contacts */
		/* TODO: Do we need to set the department, is it not retreivable from the Location ID TBD */
		
		int lSizeOfList = lListContacts.size();
		for(int lCounter = 0; lCounter< lSizeOfList; lCounter++)
		{
			CContact lContact = lListContacts.get(lCounter);
			lContact.setLocationId(mLocationId);
			lContact.setDepartmentName(mDeptName);
		}
		
		
		/* Let us log it to the database */
		if( (lListContacts != null )  && (lListContacts.size() > 0))
		{
			try
			{
				PersistenceManager pm = PMF.get().getPersistenceManager();
				pm.makePersistentAll(lListContacts);
				pm.close();
			}
			catch(Exception e) 
			{
				System.out.println("ERROR: PMF : Could not log to db");
			}
		}
		
		String lTestStr = "<script language=\"javascript\" type=\"text/javascript\">window.parent.fakeMessageSent(" + lMessage + ")";
	    System.out.println("Exiting upload now " + lTestStr);
	    res.getOutputStream().print("<script language=\"javascript\" type=\"text/javascript\">window.parent.fakeMessageSent(" + "\"<font color=green family=verdana> " + lMessage +   "</font>\""  +  ")</script>");
	}	      
		 
		
		
		

	
	public void updateParameter(String pName, String pValue)
	{
		if( pName.equals("clocation_id"))
		{
			setLocationId(pValue);
			System.out.println("LocationId set to " + pValue);
		}
		
		if( pName.equals("cdept_name"))
		{
			setDepartmentName(pValue);
			System.out.println("Department Name set to " + pValue);
		}
	}
}



/* Old file upload code does not handle multipart-form-data had to use Oriely's 
 * Multipart package - parser to get the job done */		

	    /*
		try 
		{
				ServletFileUpload upload = new ServletFileUpload();
				String lMessage = "";
				//upload.
			    FileItemIterator iterator = upload.getItemIterator(req);
			    while (iterator.hasNext()) 
			    {
			        FileItemStream item = iterator.next();
			        if (item.isFormField())
			        {
			        	System.out.println("Got a form field (value ignored) : " + item.getFieldName() + " - " + item.getName());
			        } 
			        else 
			        {
			        	System.out.println("Got an uploaded file: " + item.getFieldName() +
			                      ", name = " + item.getName());
			        	InputStream stream = item.openStream();
			        	CExcelReader lReader = new CExcelReader(stream);
			        	ArrayList<CContact> lListContacts = lReader.getContacts();
			        	System.out.println("Number of contacts found :  " + lListContacts.size());
			        	lMessage =  lListContacts.size() + " contacts added.";
			        }
			      }
		      
		      String lTestStr = "<script language=\"javascript\" type=\"text/javascript\">window.parent.fakeMessageSent(" + lMessage + ")";
		      System.out.println("Exiting upload now " + lTestStr);
		      res.getOutputStream().print("<script language=\"javascript\" type=\"text/javascript\">window.parent.fakeMessageSent(" + "\"<font color=green family=verdana> " + lMessage +   "</font>\""  +  ")</script>");
		      
			 }
			catch(Exception e ) 
			{
				e.printStackTrace();
			}
		}
*/